//
//  HouseInfoQueryController.m
//  PropertyMananger
//
//  Created by Mansion on 17/1/1.
//  Copyright © 2017年 BH. All rights reserved.
//

#import "HouseInfoQueryController.h"
#import "PullDownMenu.h"
#import "MCSearchBar.h"
#import "HouseInfoCell.h"
#import "HouseDetailController.h"
#import "HouseQueryModel.h"
#import "HouseInfoModel.h"
#import "MCUICollectionViewFlowLayout.h"
#import "LeftTableViewCell.h"

@interface HouseInfoQueryController ()<PullDownMenuDelegate,UISearchBarDelegate,UITextFieldDelegate,UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout>

@property (nonatomic,strong) PullDownMenu * menu;


@property (nonatomic,retain) NSMutableArray *arr;


@property (nonatomic,strong) UICollectionView * collectionView;
//楼栋数据源
@property (nonatomic,strong) NSMutableArray * floorArray;
@property (nonatomic,strong) NSMutableArray * tempArr;
@property (nonatomic,strong) NSMutableArray * dataArr;

//楼栋单元id
@property (nonatomic,copy) NSString * BuildUnitId;
@property (nonatomic,copy) NSString * floorStr;


//房屋信息数据源
@property (nonatomic,strong) NSMutableArray * houseInfoArray;

@end

@implementation HouseInfoQueryController
{
    NSInteger _selectIndex;
    BOOL _isScrollDown;
}
static NSString * cellID = @"infoCellID";
static  NSString * headerViewID = @"headerViewID";
//- (void)viewWillAppear:(BOOL)animated{
//
//    [self postFloorQueryData];
//    
//  [self postHouseQueryData:self.buiddingID];
//
//     [self setupSearchBar];
//}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self initTitleViewName:@"房屋信息查询"];
    
    self.floorArray = [[NSMutableArray alloc]init];
    self.tempArr = [[NSMutableArray alloc] init];
    self.dataArr = [[NSMutableArray alloc] init];
    self.houseInfoArray = [[NSMutableArray alloc] init];
    
    self.resultArr = [[NSMutableArray alloc]init];
    
    [self initTableViewWithView:self.view frame:CGRectMake(0, 0, 85, BHscreenH - 64) isGroup:NO];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.backgroundColor = [UIColor whiteColor];
    
    _selectIndex = 0;
    
    DLog(@"楼栋信息 --- %@",self.buiddingID);
    //选择楼栋
    //   [self setupBuidUnitUI];
    
    [self setupCollectionView];
    
    [self createPlaceHolder];
    
    self.searchStr = @"";
    //楼栋信息
    [self postFloorQueryData];
    
    [self postHouseQueryData:self.buiddingID];
    
     [self setupSearchBar];
    

    
    
}

#pragma mark - 搜索框
- (void)setupSearchBar
{
    UIView * bgView = [[UIView alloc]init];
    [self.view addSubview:bgView];
    bgView.backgroundColor = BHGrayColor;
    
    [bgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.equalTo(self.view).with.offset(85);
        make.top.equalTo(self.view).offset(0);
        make.size.mas_equalTo(CGSizeMake(BHscreenW - 85, 50));
    }];
    
    self.searchBar = [[MCSearchBar alloc] initWithFrame:CGRectMake(90, 7.5, BHscreenW - 100, 35) placeholder:nil];
    self.searchBar.delegate = self;
    self.searchBar.placeholder = @"请输入房间号";
    self.searchBar.barTintColor = [UIColor whiteColor];
    self.searchBar.searchTextField.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.searchBar];
    [self.searchBar setBackgroundColor:BHColor(237, 237, 237)];
    self.searchBar.layer.cornerRadius = 18.0f;
    self.searchBar.layer.masksToBounds = YES;
    self.searchBar.layer.borderWidth = 0.5;
    self.searchBar.layer.borderColor = BHColor(237, 237, 237).CGColor;
    self.searchBar.backgroundColor = [UIColor whiteColor];
    self.searchText = @"";
    
    self.searchBar.searchBarStyle = UISearchBarStyleDefault;
    
}
#pragma mark - UITableView DataSource Delegate

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.floorArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    LeftTableViewCell *cell = [LeftTableViewCell cellWithTableView:tableView];
    
    HouseQueryModel * model = self.floorArray[indexPath.row];
    cell.name.text = model.Name;
    
    return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return 50;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    _selectIndex = indexPath.row;
    HouseQueryModel * model = self.floorArray[indexPath.row];
    self.buiddingID = model.BuildUnitId;
    
    [self postHouseQueryData:self.buiddingID];
    
    // [self.collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:0 inSection:_selectIndex] atScrollPosition:UICollectionViewScrollPositionTop animated:YES];
    [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:_selectIndex inSection:0] atScrollPosition:UITableViewScrollPositionMiddle animated:YES];
}
#pragma mark - collectionView
- (void)setupCollectionView
{
    MCUICollectionViewFlowLayout *layout = [[MCUICollectionViewFlowLayout alloc] init];
    // 设置item尺寸
    layout.itemSize = CGSizeMake(80, 100);
    // 设置item之间的间隔
    layout.minimumInteritemSpacing = 10;
    // 设置行之间间隔
    layout.minimumLineSpacing = 10;
    // 设置组的内边距
    layout.sectionInset = UIEdgeInsetsMake(10, 0, 30, 30);
    
    self.collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(85, 50, BHscreenW - 85, BHscreenH - 50 - 64) collectionViewLayout:layout];
    [self.view addSubview:self.collectionView];
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    
    self.collectionView.pagingEnabled = YES;
    self.collectionView.bounces = NO;
    
    self.collectionView.showsHorizontalScrollIndicator = NO;
    self.collectionView.showsVerticalScrollIndicator = NO;
    self.collectionView.backgroundColor = BHGrayColor;
    
    [self.collectionView registerClass:[HouseInfoCell class] forCellWithReuseIdentifier:cellID];
    
    
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    if (self.isSearch) {
        return self.resultArr.count ;
    }else{
        //  return self.isSearch ? self.houseInfoArray.count : 0;
        return self.houseInfoArray.count;
    }
    
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    
    HouseInfoCell * infoCell = [collectionView dequeueReusableCellWithReuseIdentifier:cellID forIndexPath:indexPath];
    if (self.isSearch) {
        infoCell.infoTitleLabel.text = self.resultArr[indexPath.row];
    }else{
        HouseInfoModel * infoModel  = self.houseInfoArray[indexPath.row];
        infoCell.infoTitleLabel.text = infoModel.RoomName;
    }
    return infoCell;
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    [collectionView deselectItemAtIndexPath:indexPath animated:YES];
    HouseDetailController * houseDetailVC = [[HouseDetailController alloc]init];
    //  houseDetailVC.houseNum = self.arr[indexPath.row];
    HouseInfoModel * model = self.houseInfoArray[indexPath.row];
    houseDetailVC.detailModel = model;
    DLog(@"detailModel == %@",houseDetailVC.detailModel);
    [self.navigationController pushViewController:houseDetailVC animated:YES];
}
//组头
//这个方法是返回 Header的大小 size
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section
{
    return CGSizeMake(BHscreenW, 10);
}
// CollectionView分区标题即将展示
- (void)collectionView:(UICollectionView *)collectionView willDisplaySupplementaryView:(UICollectionReusableView *)view forElementKind:(NSString *)elementKind atIndexPath:(NSIndexPath *)indexPath
{
    // 当前CollectionView滚动的方向向上，CollectionView是用户拖拽而产生滚动的（主要是判断CollectionView是用户拖拽而滚动的，还是点击TableView而滚动的）
    if (!_isScrollDown && collectionView.dragging)
    {
        [self selectRowAtIndexPath:indexPath.section];
    }
}

// CollectionView分区标题展示结束
- (void)collectionView:(UICollectionView *)collectionView didEndDisplayingSupplementaryView:(nonnull UICollectionReusableView *)view forElementOfKind:(nonnull NSString *)elementKind atIndexPath:(nonnull NSIndexPath *)indexPath
{
    // 当前CollectionView滚动的方向向下，CollectionView是用户拖拽而产生滚动的（主要是判断CollectionView是用户拖拽而滚动的，还是点击TableView而滚动的）
    if (_isScrollDown && collectionView.dragging)
    {
        [self selectRowAtIndexPath:indexPath.section + 1];
    }
}

// 当拖动CollectionView的时候，处理TableView
- (void)selectRowAtIndexPath:(NSInteger)index
{
    [self.tableView selectRowAtIndexPath:[NSIndexPath indexPathForRow:index inSection:0] animated:YES scrollPosition:UITableViewScrollPositionMiddle];
}

#pragma mark - UIScrollView Delegate
// 标记一下CollectionView的滚动方向，是向上还是向下
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    static float lastOffsetY = 0;
    
    if (self.collectionView == scrollView)
    {
        _isScrollDown = lastOffsetY < scrollView.contentOffset.y;
        lastOffsetY = scrollView.contentOffset.y;
    }
}

-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
    
    if (searchText.length == 0) {
        self.searchText = @"";
        self.isSearch = NO;
        [self.houseInfoArray removeAllObjects];
        [self.tableView.mj_header beginRefreshing];
        
        [self.collectionView reloadData];
        self.placehoderImg.hidden = NO;
        self.titleLabel.hidden = NO;
        
    }
    
    self.searchText = searchText;
    NSLog(@" --- %@",self.searchText);
    self.searchStr = searchText;
    
    [self.resultArr removeAllObjects];
    [self.houseInfoArray removeAllObjects];
    
    [self.collectionView reloadData];
    
    
    for (HouseInfoModel * infoModel in self.houseInfoArray) {
        if ([infoModel.RoomName rangeOfString:searchText].location != NSNotFound) {
            [self.resultArr addObject:infoModel.RoomName];
            DLog(@"搜索结果个数 == %ld",self.resultArr.count);
        }
    }
    if (self.resultArr.count) {
        
        self.isSearch = YES;
        self.placehoderImg.hidden = YES;
        self.titleLabel.hidden = YES;
        
        [self.collectionView reloadData];
    }
}
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{
    
    //数据请求

    self.isDown = YES;
    [self postHouseQueryData:self.buiddingID];
    
    [self.tableView.mj_header beginRefreshing];
    
     [self.view endEditing:YES];

    
}
-(BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar
{
    
    return YES;
}

- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
{
    self.isDown = YES;
    self.nextPage = 1;
    
    [self postHouseQueryData:self.buiddingID];
    
    self.isSearch = NO;
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:YES];
    [self.view resignFirstResponder];
    [self.collectionView endEditing:YES];
    self.isSearch = NO;
    
}
- (BOOL)searchBar:(UISearchBar *)searchBar shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
    
    DLog(@"--------%zd--------%zd",range.length,range.location);
    if (range.location == 0) {
        
        [self.houseInfoArray removeAllObjects];
        [self.collectionView reloadData];
        
        self.placehoderImg.hidden = NO;
        self.titleLabel.hidden = NO;
    }
    
    return YES;
}

#pragma mark - 获取楼栋信息
- (void)postFloorQueryData
{
    NSDictionary * parms = @{
                             @"CommunityID":userModel.CommunityID,
                             @"json":@"\{\"jsonEntity\":\{},\"action\":\"getbuilding\",\"version\":\"V1.0\"}"};
    [HomeNetWorkRequest postFloorQuerySuccess:^(id data) {
        
        NSDictionary * dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        
        NSString * str = [NSString stringWithFormat:@"%@",dict[@"Data"]];
        NSData * data2 = [str dataUsingEncoding:NSUTF8StringEncoding];
        NSArray * array = [NSJSONSerialization JSONObjectWithData:data2 options:NSJSONReadingMutableContainers error:nil];
        DLog(@"楼栋信息的数据 == %@",array);
        if (array.count != 0) {
            
            for (NSDictionary * dict in array) {
                
                HouseQueryModel * model = [[HouseQueryModel alloc]init];
                
                [model setValuesForKeysWithDictionary:dict];
                
                [self.floorArray addObject:model];
                
            }
            
        }
        
        [self.tableView reloadData];
        
        [self.tableView selectRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] animated:YES scrollPosition:UITableViewScrollPositionTop];
        
    } Fail:^(NSString *errorDes) {
        
    } param:parms];
    
}
#pragma mark - 获取房屋信息
- (void)postHouseQueryData:(NSString *)BuildUnitId
{
    NSDictionary * parms = nil;
    
    parms = @{@"CommunityID":userModel.CommunityID,
              @"BuildUnitId":BuildUnitId,
              @"RoomName":self.searchStr,
              @"json":@"\{\"jsonEntity\":\{},\"action\":\"getroomlist\",\"version\":\"V1.0\"}"};
    
    DLog(@"提交的参数 == %@",parms);
    
    [HomeNetWorkRequest postHouseQuerySuccess:^(id data) {
        
        NSDictionary * dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        
        [self.houseInfoArray removeAllObjects];
        
        
        NSString * str = [NSString stringWithFormat:@"%@",dict[@"Data"]];
        NSData * data2 = [str dataUsingEncoding:NSUTF8StringEncoding];
        NSArray * array = [NSJSONSerialization JSONObjectWithData:data2 options:NSJSONReadingMutableContainers error:nil];
        DLog(@"房屋信息的数据 == %@",array);
        
        for (NSDictionary * dict in array) {
            
            HouseInfoModel * infoModel = [[HouseInfoModel alloc]init];
            [infoModel setValuesForKeysWithDictionary:dict];
            [self.houseInfoArray addObject:infoModel];
            DLog(@"%@",infoModel.LongRoomName);
            DLog(@"房屋信息个数 == %ld",self.houseInfoArray.count);
            self.menu.cell.textLabel.text = infoModel.BuildUnitId;
            DLog(@"self.menu.cell == %@",self.menu.cell.textLabel.text);
            
        }
        
        if (self.houseInfoArray.count != 0) {
            
            self.placehoderImg.hidden = YES;
            self.titleLabel.hidden = YES;
            
        }else{
        
            self.placehoderImg.hidden = NO;
            self.titleLabel.hidden = NO;
        }
        
        [self.collectionView reloadData];
    } Fail:^(NSString *errorDes) {
        
    } param:parms];
    
}
#pragma mark - 暂未图
- (void)createPlaceHolder
{
    self.placehoderImg = [[UIImageView alloc]init];
    [self.collectionView addSubview:self.placehoderImg];
    self.placehoderImg.image = [UIImage imageNamed:@"ico_query_no"];
    
    [self.placehoderImg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.collectionView).with.offset(0);
        make.top.equalTo(self.collectionView.mas_bottom).with.offset(100);
        make.size.mas_equalTo(CGSizeMake(80, 80));
    }];
    
    self.titleLabel = [[UILabel alloc]init];
    [self.collectionView addSubview:self.titleLabel];
    self.titleLabel.text = @"暂无查询内容";
    
    self.titleLabel.textColor= BHColor(153, 153, 153);
    self.titleLabel.font = BHFont(15);
    self.titleLabel.textAlignment = NSTextAlignmentCenter;
    
    [self.titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.collectionView).with.offset(0);
        make.top.equalTo(self.placehoderImg.mas_bottom).with.offset(10);
        make.size.mas_equalTo(CGSizeMake(100, 25));
    }];
    
    
}

@end
